package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MythreadExecutor {
    private List<Thread> threadList = new ArrayList<>();
    //用来保存任务的队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    //通过n指定创建多少个线程
    public MythreadExecutor(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() ->{
            //线程要做的事情就是要把任务队列中的任务不停的取出来并且执行
                while (true) {
                    try {
                Runnable runnable = queue.take();//take带有阻塞功能,如果队列为空,此处的take就会阻塞
                        //取出一个任务就执行一个任务
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
            threadList.add(t);
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);

    }
}
public class ThreadDemo33 {
    public static void main(String[] args) throws InterruptedException {
        MythreadExecutor executor = new MythreadExecutor(4);
        for (int i = 0; i < 1000; i++) {
            int n = i;//这样是为了防止变量捕获,每次循环是个新的n,它就是一个"事实final"n本身没有改变,就可以被捕获
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务" + n +", 当前线程为: " + Thread.currentThread().getName());
                }
            });
        }

    }
}
